import React, { Component } from 'react'

export default class App extends Component {

  state = {
    note: '',
    str: '老北京炸酱面',
    option: [
      {val: 'pg', label: '苹果'},
      {val: 'mg', label: '芒果'},
      {val: 'cm', label: '草莓'},
    ],
    sex: '',
    hobby: []
  }

  changValue = (event)=>{
    this.setState({
      [event.target.name]: event.target.value
    })
  }

  changeHobby = (event) => {
    // console.log(event.target.value, event.target.checked);

    const arr = [...this.state.hobby]

    if(event.target.checked){
      // 该项已经被选中了，应该被加在数组中
      arr.push(event.target.value)
    }else {
      // 该项已经被取消选中了，应该在数组中将其删除掉
      // 根据匹配到的内容找到索引值
      // const index = this.state.hobby.findIndex(item => event.target.value === item)
      const index = this.state.hobby.findIndex((item, index, arr) => {
        return event.target.value === item
      })

      arr.splice(index, 1)
    }


    this.setState({
      hobby: arr
    })

  }

  render() {
    return (
      <div>
        <h3> {this.state.note} </h3>
        <textarea value={this.state.note} name='note' onChange={this.changValue}></textarea>

        <select name='str' value={this.state.str} onChange={this.changValue}>
          <option value="刀削面条">刀削面条</option>
          <option value="老北京炸酱面">老北京炸酱面</option>
          <option value="青椒肉丝">青椒肉丝</option>
          <option value="黄焖鸡">黄焖鸡</option>
        </select> --------- {this.state.str}

        <select name='str' value={this.state.str} onChange={this.changValue}>
          {this.state.option && this.state.option.map(item => {
            return (<option key={item.val}> {item.label} </option>)
          })}
        </select> --------- {this.state.str}
          <br />

        <input type="radio" name="sex" value='男' onChange={this.changValue} />男
        <input type="radio" name="sex" value='女' onChange={this.changValue} />女
          --------- 你选中的是： {this.state.sex}
          <br />


          <input type="checkbox" name="hobby" value='睡觉' onChange={this.changeHobby} />睡觉
          <input type="checkbox" name="hobby" value='学习' onChange={this.changeHobby} />学习
          <input type="checkbox" name="hobby" value='干饭' onChange={this.changeHobby} />干饭
          <input type="checkbox" name="hobby" value='散步' onChange={this.changeHobby} />散步
          <input type="checkbox" name="hobby" value='钓鱼' onChange={this.changeHobby} />钓鱼
          <input type="checkbox" name="hobby" value='购物' onChange={this.changeHobby} />购物
          <br />
          ------- 你周末要做什么： {this.state.hobby}

      </div>
    )
  }
}
